package com.luisliuyi.demo.optimize.apkchannel;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;


import com.luisliuyi.lib.apk.ApkParser;
import com.luisliuyi.lib.apk.data.Apk;
import com.luisliuyi.lib.apk.data.Constants;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ChannelHelper {
    private static final String TAG = "ChannelHelper";

    private static String channel = null;


    public static String getChannel(Context context) {
        if (channel != null) {
            return channel;
        }
        try {
            Apk apk = ApkParser.parser(context.getApplicationInfo().sourceDir);
            Log.i("test","APK is V2:"+apk.isV2());
            if (apk.isV2()) {
                return v2Channel(apk);
            } else if (apk.isV1()) {
                return v1Channel(apk);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String v1Channel(Apk apk) throws UnsupportedEncodingException {
        ByteBuffer data = apk.getEocd().getData();
        short commentlen = data.getShort(Constants.EOCD_COMMENT_LEN_OFFSET);
        if (commentlen == 0) {
            return null;
        }
        byte[] commentBytes = new byte[commentlen];
        data.position(Constants.EOCD_COMMENT_OFFSET);
        data.get(commentBytes);
        channel = new String(commentBytes, Constants.CHARSET);
        return channel;
    }

    private static String v2Channel(Apk apk) throws UnsupportedEncodingException {
        ByteBuffer byteBuffer = apk.getV2SignBlock().getPair().get(Constants
                .APK_SIGNATURE_SCHEME_V2_CHANNEL_ID);
        channel = new String(byteBuffer.array(), Constants.CHARSET);
        return channel;

    }
}
